package com.konsung.ksdc.common.mqtt.parser;

import com.j256.ormlite.dao.Dao;
import com.konsung.ksdc.bean.MqttMsgBean;
import com.konsung.ksdc.bean.MqttMsgNotice;
import com.konsung.ksdc.common.database.DatabaseHelper;
import com.konsung.ksdc.common.mqtt.MqttMsgUtils;
import com.konsung.ksdc.common.utils.DateUtils;
import com.konsung.ksdc.common.utils.FileUtils;
import com.konsung.ksdc.common.utils.StringUtils;
import com.konsung.ksdc.config.MyApplication;
import com.konsung.ksdc.config.NetConfig;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.UUID;

/**
 * 声音消息处理器
 * Created by andy on 2017/4/19.
 */
public class VoiceMessageHandler extends MqttMessageHandler {

    @Override
    public byte[] parseMessage(MqttMsgBean bean) throws Exception {
        String header = getMessageHeader(bean);
        header += StringUtils.appendTime(bean.getTimeCount());
        // 如果文件不存在，则返回空消息
        File f = new File(bean.getMsgContent());
        if (!f.exists() || !f.isFile()) {
            return (header + "").getBytes();
        }

        // 读取语音文件
        InputStream in = null;
        byte[] buffer = new byte[(int) f.length()];
        try {
            in = new FileInputStream(f);
            in.read(buffer);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return byteArrayConcat(header.getBytes(), buffer);
    }

    @Override
    public MqttMsgBean parseMessage(String topicName, byte[] bytesContent) throws Exception {
        MqttMsgBean bean = fillMsgBeanHeader(topicName, bytesContent);
        String filePath = buildVoiceContent(bytesContent);
        bean.setMsgContent(filePath);
        bean.setTimeCount(Long.parseLong(new String(Arrays.copyOfRange(bytesContent, 48, 53))));
        return bean;
    }

    /**
     * 构建语音消息
     * @param content 内容
     * @return 声音内容
     */
    public static String buildVoiceContent(byte[] content) {
        byte[] voiceContent = Arrays.copyOfRange(content, MSG_VOICE_CONTENT_START, content.length);
        String voiceName = UUID.randomUUID().toString() + ".amr";
        File file = new File(FileUtils.getSavePath(voiceName));

        OutputStream out = null;
        try {
            out = new FileOutputStream(file);
            out.write(voiceContent);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file.getPath();
    }

    @Override
    public void writeNotice(String topicName, String isRead, MqttMsgBean msg) throws Exception {
        long timestamp = 0;
        try {
            timestamp = DateUtils.getDateFormat(msg.getMsgSendDate(),
                    DateUtils.yyyyMMddHHmmss).getTime();
        } catch (Exception e) {
            e.printStackTrace();
        }

        MqttMsgNotice notice = new MqttMsgNotice();
        notice.setTopicName(topicName);
        notice.setIsRead(isRead);
        notice.setTargetType(msg.getMsgTargetType());
        notice.setLastPublishUsrId(msg.getContact());
        notice.setTimestamp(timestamp);
        notice.setOwnerUserId(NetConfig.currentUser.getUserId());
        // 最多显示12个长度的字符
        notice.setNoticeMsg("[语音消息]");

        Dao dao = DatabaseHelper.getHelper(MyApplication.getContext()).getDao(MqttMsgNotice.class);
        dao.createOrUpdate(notice);
    }

    @Override
    public void hanlderReceivedMessage(String topicName, byte[] datas) throws Exception {
        MqttMsgBean msg = this.parseMessage(topicName, datas);
        if (topicName.length() > 30) {
            //因为群组的主题长度大于>30,个人的主题小于30
            if (!isGroupExits(topicName)) {
                //没有该群组
                return;
            }
        }
        // 将消息写入数据库
        DatabaseHelper.getHelper(MyApplication.getContext()).getDao(MqttMsgBean.class).create(msg);

        // 写入消息提醒
        if (MqttMsgUtils.MSG_TARGET_TYPE_PERSONAL.equals(msg.getMsgTargetType())) {
            writeNotice(msg.getContact(), "N", msg);
        } else {
            writeNotice(topicName, "N", msg);
        }

        sendBroadcast(msg);
        playSound();
    }
}
